/**
* @Description: 商品活动 - 编辑
* @author  qgj
* @date 2023/3/20
*/

<template>
  <div class="mh100">
    <div class="page-container">
      <el-form ref="form" :model="form" :rules="rules" label-width="86px">
        <div class="split-content-info" id="ruleTop">
          <!-- 标题 -->
          <div class="split-content-title clearfix">
            <div class="split-title">
              <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
              <span style="display: inline-block; color: #333333; font-size: 16px;">基本信息</span>
            </div>
          </div>
          <el-row>
            <el-col :span="6">
              <el-form-item label="活动名称:" prop="name">
                <el-input
                  placeholder="请输入"
                  v-model="form.name"
                  clearable
                  maxlength="50"
                  size="small"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="活动类型:" prop="type">
                <el-select v-model="form.type" placeholder="请选择" disabled size="small" style="width:100%">
                  <el-option
                    v-for="item in dict.type.goods_activity_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="状态:" prop="status">
                <el-select v-model="form.status" placeholder="请选择" size="small" style="width:100%">
                  <el-option
                    v-for="item in dict.type.order_class_status"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="生效日期:" prop="startDate">
                <el-date-picker
                  v-model="form.startDate"
                  type="date"
                  style="width:100%"
                  @change="changeStartDate"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6" >
              <el-form-item label="失效日期:" prop="endDate">
                <el-date-picker
                  v-model="form.endDate"
                  type="date"
                  style="width:100%"
                  @change="changeEndDate"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6"></el-col>
            <el-col :span="6"></el-col>
            <el-col :span="6"></el-col>
          </el-row>
          <el-row>
            <el-col :span="24" >
              <el-form-item label="活动说明:">
                <el-input v-model="form.activityDesc" :autosize="{ minRows: 2, maxRows: 12}" type="textarea" placeholder="请输入内容" rows="2" maxlength="500" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" >
              <el-form-item label="备注:">
                <el-input v-model="form.remark" :autosize="{ minRows: 2, maxRows: 12}" type="textarea" placeholder="请输入内容" rows="2" maxlength="500" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 模块分割线 -->
        <div class="split-line"></div>
        <!-- 模块分割线 -->
        <div class="split-content-info" :style="{minHeight: height + 'px'}">
          <div class="split-content-title clearfix" style="margin-bottom: 0px;">
            <div class="split-title">
              <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
              <span style="display: inline-block; color: #333333; font-size: 16px;">活动规则</span>
            </div>
            <div class="clearfix" style="padding-bottom: 10px">
              <el-button style="float: right;" type="primary" icon="el-icon-plus" size="small" @click="addRule">添加规则</el-button>
            </div>
          </div>
          
          <div>
            <el-table
              :data="form.activityRuleDtoList	" 
              ref="filterTable"
            >
              <el-table-column label="序号" align="left" type="index" width="60"/>
              <el-table-column label="品牌" align="left" prop="brandTypes" min-width="180">
                <template slot-scope="scope">
                  <div style="display: flex; align-items: center;" v-for="(ent, index) in scope.row.brandTypes" :key="index">
                    <a class="el-icon-circle-plus-outline" v-if="index == 0" @click.stop="addBrandType(scope.row)" style="font-size: 16px; color: #1890FF; margin-right: 10px;"></a>
                    <el-select v-model="ent.brandType" placeholder="请选择"  clearable size="small" :style="{'margin-top': index !== 0 ? '5px':'0px', 'padding-left': index !== 0 ? '25px':'0px'}">
                      <el-option v-for="item in dict.type.basic_data_goods_brand" :key="item.value" :label="item.label" :value="item.value"/>
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="商品分类" align="left" prop="goodsTypes" min-width="160">
                <template slot-scope="scope">
                  <div v-for="(ent, index) in scope.row.goodsTypes" :key="index">
                    <el-select v-model="ent.goodsType" placeholder="请选择" size="small" :style="{'margin-top': index !== 0 ? '5px':'0px'}">
                      <el-option v-for="item in goodsClassOptions" :key="item.goodsClassCode" :label="item.goodsClassName" :value="item.goodsClassCode"/>
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="比较对象" align="left" prop="compareTarget" min-width="140">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.compareTarget" placeholder="请选择" size="small">
                    <el-option v-for="item in dict.type.compare_target" :key="item.value" :label="item.label" :value="item.value"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="比较符" align="left" prop="compareSymbolLeft" min-width="120">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.compareSymbolLeft" placeholder="请选择" size="small" @change="changeValueTo(scope.row)" clearable>
                    <el-option v-for="item in dict.type.compare_symbol_left" :key="item.value" :label="item.label" :value="item.value"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="比较数值从" align="left" prop="compareValueFrom" min-width="170">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.compareValueFrom"
                    maxlength="10"
                    size="small"
                    clearable
                    :disabled="scope.row.compareSymbolLeft?false:true"
                    oninput="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                    placeholder="请输入"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="比较符" align="left" prop="compareSymbolRight" min-width="120">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.compareSymbolRight" placeholder="请选择" size="small" @change="changeValueTo(scope.row)" clearable>
                    <el-option v-for="item in dict.type.compare_symbol_right" :key="item.value" :label="item.label" :value="item.value"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="比较数值至" align="left" prop="compareValueTo" min-width="170">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.compareValueTo"
                    maxlength="10"
                    clearable
                    :disabled="scope.row.compareSymbolRight?false:true"
                    size="small"
                    oninput="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                    placeholder="请输入"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="ERP价目表" align="left" prop="priceCodes" min-width="140">
                <template slot-scope="scope">
                  <div v-for="(ent, index) in scope.row.priceCodes">
                    <el-select v-model="ent.priceCode" placeholder="请选择" filterable size="small" :style="{'margin-top': index !== 0 ? '5px':'0px'}">
                      <el-option v-for="item in priceCodeOptions" :key="item.priceCode" :label="item.priceName" :value="item.priceCode"/>
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" align="left" class-name="small-padding fixed-width" width="120">
                <template slot-scope="scope">
                  <div v-for="(ent, index) in scope.row.brandTypes" :style="{'height': '32px','margin-top': index !== 0 ? '5px':'0px'}">
                    <el-button size="mini" type="text" icon="el-icon-key" @click="handleDel(scope.row, index)" style="margin-top: 1px;">删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form>
      <div class="h84_line"></div>
      <div class="bottom-btn">
        <div class="bottom-locate" >
          <el-button type="default" @click="cancel">取消</el-button>
          <el-button type="primary" :loading="saveLoading" @click="save">确认</el-button>
        </div>
      </div>

    </div>
  </div>
</template>

<script>

import {getGoodsTypeList, getPriceList, updateGoodsActivity, getGoodsActivity} from '@/api/basic/activity'
export default {
  name: 'CommodityActivityEdit',
  dicts: ['order_class_status', 'basic_data_goods_brand', 'goods_activity_type', 'compare_target', 'compare_symbol_left', 'compare_symbol_right'],
  data() {
    return {
      // tableHeight: 700,
      height: 130,
      title: '配置收货地区',
      filterText: '', // 搜索地区
      saveLoading: false,
      labelPosition: "right",     // 表单label对齐方式
      form: {
        name: undefined, // 活动名称
        type: undefined, // 活动类型
        status: undefined, // 状态
        startDate: undefined, //生效日期
        endDate: undefined, //失效日期
        activityDesc: undefined, // 活动说明
        remark: undefined, // 备注
        activityRuleDtoList: [], // 活动规则
      },
      rules: {
        name: [
            {required: true, message: "请输入活动名称", trigger: "blur"}
        ],
        startDate: [
            {required: true, message: '请选择日期', trigger: 'change' }
        ]
      },
      goodsClassOptions:[], //商品分类
      priceCodeOptions:[
        {
          priceCode: "1",
          priceName: "默认价格"
        }
      ], //ERP价目表
      activityId:''
    }
  },
  created() {},
  mounted() {
    this.getClassList();
    this.getActivityDetail();
    // 解决表格设置固定高度导致列设置fixed后重新进来会错行问题
    this.tableHeight();
  },
  activated() {
    // 解决表格设置固定高度导致列设置fixed后重新进来会错行问题
    this.tableHeight();
  },
  watch: {
    $route() {
        this.getClassList();
        this.getActivityDetail();
    },
  },
  methods: {
    tableHeight() {
      this.$nextTick(() => {
        let height = document.body.clientHeight - 90 - 40;// - 62 - 20;
        // 查询表单高度
        let s_height = document.getElementById('ruleTop').clientHeight;
        // 按钮容器高度
        // let btns_height = document.getElementById('comTabel').clientHeight;
        // 计算表格的高度
        this.height = height - s_height - 20 - 64;
      });
    },

    // 表单重置
    reset() {
      this.form = {
        name: undefined, // 活动名称
        type: undefined, // 活动类型
        status: undefined, // 状态
        startDate: undefined, //生效日期
        endDate: undefined, //失效日期
        activityDesc: undefined, // 活动说明
        remark: undefined, // 备注
        activityRuleDtoList: [], // 活动规则
      }
      this.resetForm("form");
    },

    //获取活动详情
    getActivityDetail() {
      if(this.$route.query.activityId){
        this.reset();
        const str = JSON.parse(this.$route.query.activityId)
        this.activityId = JSON.parse(this.$route.query.activityId)
        getGoodsActivity(str).then(response => {
          console.log('res=', response.data);
          // this.form = response.data
          const list = response.data.activityRuleDtoList;
          let groupItem = undefined;
          let addList = [];
          const count = list.length;
          list.forEach((item, index) => {
            this.$set(item, 'brandTypes', []);
            this.$set(item, 'goodsTypes', []);
            this.$set(item, 'priceCodes', []);
            if (item.groupCode == undefined || item.groupCode == null || item.groupCode == '' || item.groupCode.length == 0) {
              item.groupCode = index;
            }

            if (groupItem == undefined) {
              groupItem = JSON.parse(JSON.stringify(item));
            }
            if (groupItem.groupCode == item.groupCode) { // 表示在一个组
              groupItem.brandTypes.push({brandType: item.brandType});
              groupItem.goodsTypes.push({goodsType: item.goodsType});
              groupItem.priceCodes.push({priceCode: item.priceCode});
              if (count == index + 1) { // 表示数组的最后条
                addList.push(JSON.parse(JSON.stringify(groupItem)));
                groupItem = undefined;
              }
            } else { // 不同
              addList.push(JSON.parse(JSON.stringify(groupItem)));
              // 下一个
              groupItem = JSON.parse(JSON.stringify(item));;
              groupItem.brandTypes.push({brandType: item.brandType});
              groupItem.goodsTypes.push({goodsType: item.goodsType});
              groupItem.priceCodes.push({priceCode: item.priceCode});
              if (count == index + 1) { // 表示数组的最后条
                addList.push(JSON.parse(JSON.stringify(groupItem)));
                groupItem = undefined;
              }
            }
          });
          this.form = JSON.parse(JSON.stringify(response.data));
          this.form.activityRuleDtoList = addList;
          // console.log('addList=', addList);
        })
      }
    },

    /** 获取商品分类、ERP价目表*/
    getClassList() {
      getGoodsTypeList().then(response => {
          this.goodsClassOptions = response.data
      });
      getPriceList().then(response=>{
        this.priceCodeOptions = [
          {
            priceCode: "1",
            priceName: "默认价格"
          }
        ]
        // this.priceCodeOptions = response.data
        response.data.map(item=>{
          this.priceCodeOptions.push(item)
        })
      })
    },

    /**
     * 添加规则
     */
    addRule() {
      let params = {
        brandType: '', // 品牌类型
        brandTypes: [{brandType: ''}], // 平拍类型列表
        goodsType: '', // 商品分类
        goodsTypes: [{goodsType: ''}], // 商品分类列表
        compareTarget: 'BUYAMOUNT', //比较对象
        compareSymbolLeft: '', // 左侧比较符
        compareSymbolRight: '', // 左侧比较符
        compareValueFrom: null,  // 比较数值从
        compareValueTo: null,  // 比较数值至
        priceCode: '', // ERP价目表
        priceCodes: [{priceCode: ''}], // ERP价目表列表
        groupCode: this.form.activityRuleDtoList.length + 1, // 分组编号
      };
      this.form.activityRuleDtoList.push(params);
    },

    /**
     * 添加品牌
     * @param {*} row 
     */
     addBrandType(row) {
      row.brandTypes.push({brandType: ''}); // 品牌
      row.goodsTypes.push({goodsType: ''}); // 商品分类
      row.priceCodes.push({priceCode: ''}); // 价目表
    },

    /** 比较数值验证 */
    changeValueTo(val) {
      console.log(val,this.form.activityRuleDtoList)
      if(val.compareSymbolLeft == ''){
        val.compareValueFrom = ""
      }
      if(val.compareSymbolRight == ''){
        val.compareValueTo = ""
      }
    },

    /**
     * 过滤属性结构的数据
     * @param {*} value 
     * @param {*} data 
     */
    filterNodeArea(value, data) {
      if (!value) {
        return true;
      }
      return data.name.indexOf(value) !== -1;
    },

    /** 删除 */
    handleDel(row, index) {
      if (row.brandTypes.length !== 1) {
        row.brandTypes.splice(index, 1);
        row.goodsTypes.splice(index, 1);
        row.priceCodes.splice(index, 1);
      } else {
        this.form.activityRuleDtoList.splice(this.form.activityRuleDtoList.indexOf(row), 1);
      }
    },

    /** 关闭 */
    cancel() {
      const obj = { path: "/basicData/commodityActivity" };
      this.$tab.closeOpenPage(obj);
    },
    //日期大小判断
    changeStartDate(val) {
      if(val && this.form.endDate){
        let date1 = new Date(val)
        let date2 = new Date(this.form.endDate)
        if(date1.getTime()>date2.getTime()){
          this.$modal.msgWarning("生效日期不能大于失效日期");
          this.form.startDate = ''
        }
      }
    },
    changeEndDate(val){
      if(val && this.form.startDate){
        let date1 = new Date(val)
        let date2 = new Date(this.form.startDate)
        if(date1.getTime()<date2.getTime()){
          this.$modal.msgWarning("失效日期不能小于生效日期");
          this.form.endDate = ''
        }
      }
    },

    /**
     * 获取价目表名称
     * @param {*} code 
     */
     getPriceCodeName(code) {
      let show = '';
      this.priceCodeOptions.some(item => {
        if (item.priceCode == code) {
          show = item.priceName;
          return true;
        }
      });
      return show;
    },

    /**
     * 得到商品分类名称
     * @param {*} code 
     */
    getGoodsTypeName(code) {
      let show = '';
      this.goodsClassOptions.some(item => {
        if (item.goodsClassCode == code) {
          show = item.goodsClassName;
        }
      });
      return show;
    },

    //保存提交
    save() {

      let someData = [];
      let arr = this.form.activityRuleDtoList;
      if (arr.length == 0) {
        this.$modal.msgWarning("活动规则不能为空！");
        return;
      }
      let bret = false;
      arr.some(row => {
        bret = false;
        row.brandTypes.some((item, index) => {
          bret = false;
          const brandType = item.brandType; // 品牌
          const goodsType = row.goodsTypes[index].goodsType; // 商品分类
          const priceCode = row.priceCodes[index].priceCode; // ERP价目表
          const brandGoods = brandType + goodsType;
          someData.push(brandGoods);
          if (goodsType == undefined || goodsType == '') {
            this.$modal.msgWarning("商品分类不能为空！")
            bret = true;
            return true;
          }
          if (priceCode == undefined || priceCode == '') {
            this.$modal.msgWarning("ERP价目表不能为空！")
            bret = true;
            return true;
          }
        });
        if (bret) {
          return bret;
        }
      });
      const newList = new Set(someData);
      console.log('someData=', someData);
      console.log('newList', newList);
      console.log('someData.len=', someData.length, '; newList.len=', newList.size);
      if (someData.length > newList.size) {
        this.$modal.msgWarning("存在一致的品牌和商品分类规则，只能添加一条数据！");
        return;
      }
      if (bret) {
        return;
      }
      
      this.$refs["form"].validate(valid => {
        let formCopy = JSON.parse(JSON.stringify(this.form));
        let datas = [];
        formCopy.activityRuleDtoList.forEach(row => {
          row.brandTypes.forEach((item, index) => {
            let addItem = JSON.parse(JSON.stringify(row));
            addItem.brandType = item.brandType; // 品牌
            addItem.goodsType = row.goodsTypes[index].goodsType; // 商品分类
            addItem.goodsTypeName = this.getGoodsTypeName(addItem.goodsType); // 商品分类名称
            addItem.priceCode = row.priceCodes[index].priceCode; // ERP价目表
            addItem.priceName = this.getPriceCodeName(addItem.priceCode); // ERP价目表名称
            datas.push(addItem);
          });
        });
        formCopy.activityRuleDtoList = datas;
        let arr = formCopy.activityRuleDtoList
        if(arr.length == 0){
          this.$modal.msgWarning("活动规则不能为空！")
          return
        }
        for(let i=0;i<arr.length;i++){
          if(arr[i].goodsType == ''){
            this.$modal.msgWarning("商品分类不能为空！")
            return
          }
          if(arr[i].compareSymbolLeft == '' && arr[i].compareSymbolRight == ''){
            this.$modal.msgWarning("比较符不能都为空")
            return
          }
          if(arr[i].compareSymbolLeft != '' && arr[i].compareValueFrom == ''){
            this.$modal.msgWarning("比较数值从不能为空")
            return
          }
          if(arr[i].compareSymbolRight != '' && arr[i].compareValueTo == ''){
            this.$modal.msgWarning("比较数值至不能为空")
            return
          }
          if(arr[i].compareSymbolLeft == 'GREATEROREQUAL' && arr[i].compareSymbolRight == 'LESS'){
            if(arr[i].compareValueFrom >= arr[i].compareValueTo){
              this.$modal.msgWarning("比较符为大于等于和小于时，比较数值从不能等于或大于比较数值至")
              return
            }
          }
          if(arr[i].compareSymbolLeft == 'GREATER' && arr[i].compareSymbolRight == 'LESSOREQUAL'){
            if(arr[i].compareValueFrom >= arr[i].compareValueTo){
              this.$modal.msgWarning("比较符为大于和小于等于时，比较数值从不能等于或大于比较数值至")
              return
            }
          }
          if(arr[i].compareSymbolLeft == 'GREATER' && arr[i].compareSymbolRight == 'LESS'){
            if(arr[i].compareValueFrom >= arr[i].compareValueTo){
              this.$modal.msgWarning("比较符为大于和小于时，比较数值从不能等于或大于比较数值至")
              return
            }
          }

        }
        if (valid) {
          formCopy.startDate = this.$moment(formCopy.startDate).format("YYYY-MM-DD");
          formCopy.endDate?formCopy.endDate = this.$moment(formCopy.endDate).format("YYYY-MM-DD"):'';
          // const str = this.form;
          console.log('formCopy=', formCopy);
          updateGoodsActivity(formCopy).then(response => {
            this.$modal.msgSuccess("编辑成功");
            this.cancel();
          });
            
        }
      });

      /*
      this.$refs["form"].validate(valid => {
        let arr = this.form.activityRuleDtoList
        for(let i=0;i<arr.length;i++){
          if(arr[i].goodsType == ''){
            this.$modal.msgWarning("商品分类不能为空！")
            return
          }
          if(arr[i].compareSymbolLeft == '' && arr[i].compareSymbolRight == ''){
            this.$modal.msgWarning("比较符不能都为空")
            return
          }
          if(arr[i].compareSymbolLeft != '' && arr[i].compareValueFrom == ''){
            this.$modal.msgWarning("比较数值从不能为空")
            return
          }
          if(arr[i].compareSymbolRight != '' && arr[i].compareValueTo == ''){
            this.$modal.msgWarning("比较数值至不能为空")
            return
          }
          if(arr[i].compareSymbolLeft == 'GREATEROREQUAL' && arr[i].compareSymbolRight == 'LESS'){
            if(arr[i].compareValueFrom >= arr[i].compareValueTo){
              this.$modal.msgWarning("比较符为大于等于和小于时，比较数值从不能等于或大于比较数值至")
              return
            }
          }
          if(arr[i].compareSymbolLeft == 'GREATER' && arr[i].compareSymbolRight == 'LESSOREQUAL'){
            if(arr[i].compareValueFrom >= arr[i].compareValueTo){
              this.$modal.msgWarning("比较符为大于和小于等于时，比较数值从不能等于或大于比较数值至")
              return
            }
          }
          if(arr[i].compareSymbolLeft == 'GREATER' && arr[i].compareSymbolRight == 'LESS'){
            if(arr[i].compareValueFrom >= arr[i].compareValueTo){
              this.$modal.msgWarning("比较符为大于和小于时，比较数值从不能等于或大于比较数值至")
              return
            }
          }
        }
        if (valid) {
          this.form.startDate = this.$moment(this.form.startDate).format("YYYY-MM-DD")
          this.form.endDate?this.form.endDate = this.$moment(this.form.endDate).format("YYYY-MM-DD"):''
          const str = this.form;
            updateGoodsActivity(str).then(response => {
              this.$modal.msgSuccess("编辑成功");
              this.cancel();
            });
        }
      });
      */
    },
  },
}
</script>